<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #otherField="{ model, field }">
        <FormItemRest>
          <div class="flex gap-10px items-center">
            <Select
              :options="fieldsDataOptions"
              v-model:value="model[field]"
              placeholder="请选择"
              style="width: 50%"
              showSearch
              optionFilterProp="label"
              @change="handleOtherField"
            />

            显示

            <Select
              :options="fieldsDataOptions2"
              v-model:value="dataRef['otherShowField']"
              placeholder="请选择"
              style="flex: 1"
              showSearch
              optionFilterProp="label"
            />
          </div>
        </FormItemRest>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import {
    mappingFieldsFormSchema,
    mappingFieldsFormSchema2,
    defaultMappingFieldList,
  } from './viewList.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { getFormGetFields } from '/@/api/flowManage/flowManage';
  import { Form, Select } from 'ant-design-vue';
  import { getFormList, getFormFields } from '/@/api/process/process';
  import { isArray } from '/@/utils/is';
  import { getVisualColAdd } from '/@/api/module/module';

  export default defineComponent({
    name: 'MappingFieldsDrawer',
    components: { BasicDrawer, BasicForm, FormItemRest: Form.ItemRest, Select },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      let dataRef = ref<any>({});
      const formFieldList = ref<Recordable[]>([]);
      const fieldsList = ref<Recordable[]>([]);
      const fieldType = ref(1);
      const formCode = ref('');
      const moduleCode = ref('');
      const [registerForm, { resetFields, setFieldsValue, validate, updateSchema, resetSchema }] =
        useForm({
          labelWidth: 110,
          schemas: mappingFieldsFormSchema,
          showActionButtonGroup: false,
        });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        formCode.value = data?.formCode ?? '';
        moduleCode.value = data?.moduleCode ?? '';
        fieldType.value = data?.fieldType; // 1是映射 2是多重映射
        dataRef.value = {};
        if (unref(isUpdate)) {
          dataRef.value = data?.record;
        } else {
          dataRef.value = {
            formCode: data?.formCode,
            code: moduleCode.value,
            fieldType: data?.fieldType,
            fieldOrder: data?.dataSourceLength ? data.dataSourceLength + 1 : 1,
          };
        }
        if (unref(dataRef).fieldType == 1) {
          await resetSchema(mappingFieldsFormSchema);
          await setFieldsValue({
            ...unref(dataRef),
          });
          await getFormGetFieldsData();
          getFormData();
        } else if (unref(dataRef).fieldType == 2) {
          await resetSchema(mappingFieldsFormSchema2);
          await setFieldsValue({
            ...unref(dataRef),
          });
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

      async function handleSubmit() {
        try {
          const values = await validate();
          let formDate = Object.assign({}, unref(dataRef), values);
          setDrawerProps({ confirmLoading: true });
          console.log(formDate);
          if (unref(isUpdate)) {
            // await getVisualColAdd(formDate);
          } else {
            await getVisualColAdd(formDate);
          }
          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      //获取数据
      const getFormGetFieldsData = () => {
        formFieldList.value = [];
        console.log('getFormGetFieldsData', formCode.value);
        try {
          if (!formCode.value) return;
          getFormGetFields({ formCode: formCode.value }).then((res) => {
            formFieldList.value = res || [];
            formFieldList.value.forEach((item: Recordable) => {
              delete item.options;
              item.value = item.name;
              item.label = item.title;
            });
            fieldsList.value = [...formFieldList.value, ...defaultMappingFieldList];
            console.log('fieldsList', fieldsList.value);
            updateSchema([
              {
                field: 'fieldName',
                componentProps: {
                  options: fieldsList.value,
                  showSearch: true,
                  optionFilterProp: 'label',
                },
              },
            ]);
            if (fieldsList.value.length) {
              setFieldsValue({ fieldName: fieldsList.value[0].value });
            }
          });
        } catch (err) {
          console.log('getFormGetFields', err);
        }
      };

      const currentCode = ref('');
      const formDataOptions = ref<Recordable[]>([]);
      const getFormData = () => {
        formDataOptions.value = [];
        getFormList().then((res) => {
          formDataOptions.value = res || [];
          if (isArray(formDataOptions.value) && formDataOptions.value.length) {
            formDataOptions.value.forEach((item) => {
              item.label = item.name;
              item.value = item.code;
            });
            dataRef.value.otherFormCode = formDataOptions.value[0].value;
            setFieldsValue({ otherFormCode: dataRef.value.otherFormCode });
            if (unref(dataRef).otherFormCode) {
              handleChangeForm(unref(dataRef).otherFormCode);
            }
            updateSchema({
              field: 'otherFormCode',
              componentProps: {
                options: formDataOptions.value,
                onChange: handleChangeForm,
                showSearch: true,
                optionFilterProp: 'label',
              },
            });
          }
        });
      };

      //表单change
      const handleChangeForm = (val) => {
        currentCode.value = val;
        setFieldsValue({ otherField: 'id' });
        getFieldsData();
      };
      const handleOtherField = (val) => {
        setFieldsValue({ otherField: val });
      };
      const fieldsDataOptions = ref<Recordable[]>([]);
      const fieldsDataOptions2 = ref<Recordable[]>([]);
      //获取表单对应字段
      const getFieldsData = async () => {
        try {
          const params = {
            formCode: unref(currentCode),
          };
          fieldsDataOptions.value = (await getFormFields(params)) || [];
          fieldsDataOptions.value.forEach((item: any) => {
            delete item.options;
            item.label = item.title;
            item.value = item.name;
          });
          fieldsDataOptions2.value = [...fieldsDataOptions.value];
          fieldsDataOptions2.value.push({
            label: 'ID',
            value: 'ID',
          });
          dataRef.value['otherShowField'] = fieldsDataOptions2.value[0].value;
          fieldsDataOptions.value.unshift({
            label: 'id',
            value: 'id',
          });
          fieldsDataOptions.value.push({
            label: 'cws_id',
            value: 'cws_id',
          });
        } catch (err) {
          console.error(err);
        }
      };
      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
        fieldsDataOptions,
        fieldsDataOptions2,
        dataRef,
        handleOtherField,
      };
    },
  });
</script>
